<template>
  <view class="container">
    <view>
      <view class="header">
        <view class="title">{{ form.need_title || "未填写" }}</view>
      </view>

      <!-- 动态显示第一项：根据公司类型显示不同标题 -->
      <view class="section">
        <view class="section-title">{{ fieldLabels.primaryType }}</view>
        <view class="content">{{ form.need_type || "未填写" }}</view>
      </view>

      <!-- 预估金额：除物资采购外显示 -->
      <view class="section" v-if="form.company_type != 3">
        <view class="section-title">{{ fieldLabels.amount }}</view>
        <view class="content">{{ form.need_amount || "未填写" }}</view>
      </view>

      <!-- 规格和数量：仅物资采购显示 -->
      <view class="section" v-if="form.company_type == 3">
        <view class="section-title">规格</view>
        <view class="content">{{ form.goods_attr || "未填写" }}</view>
      </view>
      <view class="section" v-if="form.company_type == 3">
        <view class="section-title">数量</view>
        <view class="content">{{ form.goods_num || "未填写" }}</view>
      </view>

      <!-- 动态显示要求项 -->
      <view class="section">
        <view class="section-title">{{ fieldLabels.requirements }}</view>
        <view class="content">{{ form.need_yao_qiu || "未填写" }}</view>
      </view>

      <!-- 动态显示时间项 -->
      <view class="section">
        <view class="section-title">{{ fieldLabels.time }}</view>
        <view class="content">{{ form.need_time || "未填写" }}</view>
      </view>

      <view class="section">
        <view class="section-title">付款方式</view>
        <view class="content">{{ form.need_pay_type || "未填写" }}</view>
      </view>

      <view class="section">
        <view class="section-title">项目所在地</view>
        <view class="content">{{ form.need_city_name || "未填写" }}</view>
      </view>

      <!-- 动态显示公司要求项 -->
      <view class="section">
        <view class="section-title">{{ fieldLabels.companyRequirements }}</view>
        <view class="content">{{ form.company_yao_qiu || "未填写" }}</view>
      </view>
      <view class="section">
        <view class="section-title">本信息截至有效期</view>
        <view class="content">{{ form.need_ent_date || "未填写" }}</view>
      </view>
    </view>

    <view>
      <view v-if="form.view_status == 4 || form.self_fa">
        <view class="section" v-if="form.company_type == 2">
          <!-- 物资采购  -->
          <view class="section-title">采购单位</view>
          <view class="content">{{ form.need_yao_qiu || "未填写" }}</view>
        </view>
        <view class="section" v-else>
          <view class="section-title">需求单位</view>
          <view class="content">{{ form.company_name || "未填写" }}</view>
        </view>

        <view class="section">
          <view class="section-title">联系人</view>
          <view class="content">{{ form.linkman_realname || "未填写" }}</view>
        </view>
        <view class="section">
          <view class="section-title">职务</view>
          <view class="content">{{ form.linkman_duty || "未填写" }}</view>
        </view>
        <view class="section">
          <view class="section-title">电话</view>
          <view class="content">{{ form.linkman_mobile || "未填写" }}</view>
        </view>
      </view>
      <view v-else>
        <u-empty
          mode="data"
          :text="statusConfig.text"
          :icon="getResource('img/phone/mini/no_data.png')"
        />
        <!-- {{ form.view_status }} -->
        <view
          v-if="form.self_fa == false || form.view_status != 4"
          @click="handleItemClick(form)"
          style="
            display: flex;
            padding: 10px 20px;
            background-color: #007aff;
            color: white;
            border-radius: 5px;
            text-align: center;
            font-size: 16px;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            transition: background-color 0.3s;
            width: 35%;
            margin: 10px auto;
            text-align: center;
            justify-content: center;
          "
        >
          购买本条资讯
        </view>
      </view>
    </view>

    <view class="footer" v-if="form.self_fa == true && state.indexType == ''">
      <button class="btn" @click="finished">标记为已完成</button>
    </view>
    <cardPopup v-model="state.on_of" />
    <u-modal
      :show="state.modalOn_of"
      title="系统消息"
      :showCancelButton="true"
      confirmText="立即充值"
      cancelText="立即购买"
      @cancel="modalCancel(1)"
      @confirm="modalCancel(2)"
    >
      <view class="slot-content"> 您当前余额不足,立刻充值有优惠 </view>
    </u-modal>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, toRefs } from "vue";
import {
  showToast,
  showLoading,
  hideLoading,
  showModalNoCancel,
  showModal,
} from "@/utils/toast";
import { getResource } from "../../../utils/Resource";
import { getIndexPubId } from "@/api/demand.js";
import { onShow, onLoad } from "@dcloudio/uni-app";
import { Postfinish } from "../../../api/news";
import { PostNeed_id } from "@/api/news.js";

// 状态管理
const state = reactive({
  modalOn_of: false,
  on_of: false,
  dataList: [],
  count: 0,
  indexId: null,
  indexType: "",
  form: {},
});

const { form } = toRefs(state);

// 计算属性：根据公司类型动态生成字段标签
const fieldLabels = computed(() => {
  switch (Number(form.value.company_type)) {
    case 2: // 工程公司
      return {
        primaryType: "工程类型",
        amount: "预估工程费总额",
        requirements: "工程要求",
        time: "施工时间",
        companyRequirements: "对工程公司要求",
      };
    case 3: // 物资采购
      return {
        primaryType: "采购物资名称",
        amount: "预估采购费总额",
        requirements: "质量要求",
        time: "供货时间",
        companyRequirements: "对供应商质量要求",
      };
    case 4: // 设计公司
      return {
        primaryType: "设计业务类型",
        amount: "预估设计费总额",
        requirements: "设计要求",
        time: "设计时间",
        companyRequirements: "对设计公司要求",
      };
    case 5: // 监理公司
      return {
        primaryType: "监理业务类型",
        amount: "预估监理费总额",
        requirements: "监理要求",
        time: "监理时间",
        companyRequirements: "对监理公司要求",
      };
    case 6: // 劳务队伍
      return {
        primaryType: "劳务类型",
        amount: "预估劳务费总额",
        requirements: "施工要求",
        time: "施工时间",
        companyRequirements: "对劳务公司要求",
      };
    default:
      return {
        primaryType: "项目类型",
        amount: "预估费用总额",
        requirements: "项目要求",
        time: "项目时间",
        companyRequirements: "对合作方要求",
      };
  }
});

const statusConfig = computed(() => {
  const configs = {
    1: { text: "未登录" },
    2: { text: "登录未认证" },
    3: { text: "未购买" },
    4: { text: "已支付" },
  };
  return configs[form.value.view_status] || { text: "暂无数据" };
});

onLoad(async (e) => {
  try {
    state.indexId = e.id;
    if (e.type) {
      state.indexType = e.type;
    }
    await init();
  } catch (error) {
    console.error(error);
  }
});

const handleItemClick = async (e) => {
  showModal(
    {
      title: "系统消息",
      content: `购买本条信息需要花费${e.pay_amount}元，您当前的余额为${e.user_balance}`,
    },
    (result) => {
      if (result.confirm) {
        setTimeout(() => {
          PostNeed_id(e.id).then((res) => {
            if (res.data == "1") {
              dataList.value = [];
              init();
              showModal(
                {
                  title: "系统消息",
                  content: "您的已购买",
                  showCancel: false,
                },
                (result) => {}
              );
              return;
            }
            state.modalOn_of = true;
            zhiFuShuJu.value = res.data;
          });
        }, 500);
      }
    }
  );
};

const init = async () => {
  try {
    showLoading("加载中...");
    const res = await getIndexPubId({ id: state.indexId });
    console.log(res.data);
    if (res.data.need_title) {
      uni.setNavigationBarTitle({
        title: res.data.need_title,
      });
    }
    state.form = res.data;
  } catch (error) {
    console.error(error);
    showToast("加载失败");
  } finally {
    hideLoading();
  }
};

const finished = async () => {
  try {
    showLoading("处理中...");
    const res = await Postfinish(state.indexId);
    console.log(res);
    if (res.code == 10000) {
      showToast("已完成");
      setTimeout(() => {
        uni.navigateBack({
          delta: 1,
        });
      }, 500);
    }
  } catch (error) {
    console.error(error);
    showToast("操作失败");
  } finally {
    hideLoading();
  }
};

const zhiFuShuJu = ref();
const modalCancel = (e) => {
  state.modalOn_of = false;
  if (e == 1) {
    uni.requestPayment({
      provider: "wxpay",
      timeStamp: zhiFuShuJu.value.timestamp,
      nonceStr: zhiFuShuJu.value.nonceStr,
      package: zhiFuShuJu.value.package,
      signType: "MD5",
      paySign: zhiFuShuJu.value.paySign,
      success: function (res) {
        if (res.code == 10000) {
          init();
          uni.showToast({
            title: "充值成功",
            icon: "success",
            duration: 2000,
          });
        }
      },
      fail: function (err) {
        uni.showToast({
          title: "充值失败请联系管理员",
          icon: "error",
          duration: 2000,
        });
        console.log("fail:" + JSON.stringify(err));
      },
    });
  } else {
    state.on_of = true;
  }
};
</script>

<style>
.container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-2 {
  background-color: #67c23a;
  color: white;
}

.section {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.content {
  font-size: 16px;
  line-height: 1.5;
  color: #303133;
}

.footer {
  margin-top: 30px;
  text-align: center;
}

.btn {
  background-color: #409eff;
  color: white;
  border-radius: 4px;
  padding: 10px 20px;
  border: none;
  width: 100%;
  font-size: 16px;
}
</style>
